package com.luoy.threads;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class TestCountDownLatch {

	public static void main(String[] args) {
		//构造一个给定的计数器
		CountDownLatch cdl = new CountDownLatch(2);
		//
		CyclicBarrier cb = new CyclicBarrier(3); 
		
		Thread t1 = new Thread(){
			public void run(){
				for(int i = 1 ; i <= 100 ; i++){
					System.out.println("### "+i);
					//减少锁存器的计数
					if (i == 50) cdl.countDown();
					try {
						Thread.sleep(100);
						if (i == 99) cb.await();
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		};
		Thread t2 = new Thread(){
			public void run(){
				for(int i = 1 ; i <= 100 ; i++){
					System.out.println("$$$ "+i);
					//计数器减1
					if (i == 50) cdl.countDown();
					try {
						Thread.sleep(100);
						if (i==99) cb.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}			
			}
		};
		Thread t3 = new Thread(){
			public void run(){
				try {
					//无限期等待，等到计数器为0开始工作
					cdl.await();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				for(int i = 1 ; i <= 100 ; i++){
					System.out.println("*** "+i);
					try {
						Thread.sleep(100);
						if (i==99) cb.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}				
			}
		};
		t1.start();
		t2.start();
		t3.start();
	}

}
